import { SunshineNgZorroAntdModule } from '../../ng-zorro-module';
import { MyDerirective01Directive } from '../../study/directives/my-derirective01.directive';
import { SunshinePermissionDirective } from '../../study/directives/sunshine-permission.directive';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Component, Injectable, OnInit } from '@angular/core';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { RandomUser, RandomUserService } from './user.service';




@Component({
  selector: 'app-user',
  standalone: true,
  imports: [SunshineNgZorroAntdModule, MyDerirective01Directive, SunshinePermissionDirective],
  templateUrl: './user.component.html',
  styleUrl: './user.component.css'
})
export class UserComponent {
  validateForm: FormGroup = this.fb.group({
    // 设置校验规则 初始值 规则  失去焦点校验
    userName: ['12'],
    email: [12],
  });

  total = 1;
  listOfRandomUser: RandomUser[] = [];
  loading = true;
  pageSize = 10;
  pageIndex = 1;
  filterGender = [
    { text: 'male', value: 'male' },
    { text: 'female', value: 'female' }
  ];

  loadDataFromServer(
    pageIndex: number,
    pageSize: number,
    sortField: string | null,
    sortOrder: string | null,
    filter: Array<{ key: string; value: string[] }>
  ): void {
    this.loading = true;
    this.randomUserService.getUsers(pageIndex, pageSize, sortField, sortOrder, filter).subscribe(data => {
      this.loading = false;
      this.total = 200; // mock the total data here
      this.listOfRandomUser = data.results;
    });
  }

  onQueryParamsChange(params: NzTableQueryParams): void {
    console.log(params);
    const { pageSize, pageIndex, sort, filter } = params;
    const currentSort = sort.find(item => item.value !== null);
    const sortField = (currentSort && currentSort.key) || null;
    const sortOrder = (currentSort && currentSort.value) || null;
    this.loadDataFromServer(pageIndex, pageSize, sortField, sortOrder, filter);
  }

  resetForm(): void {
    this.validateForm.reset();
  }

  constructor(private fb: FormBuilder, private randomUserService: RandomUserService) { }

  ngOnInit(): void {
    this.loadDataFromServer(this.pageIndex, this.pageSize, null, null, []);
  }
}
